// 管理用户数据相关
import LoginApi from '@/api/login/index.ts'
import { setAddRoute } from '@/router/index.ts'
import { Session } from "@/utils/storage"
import { defineStore } from 'pinia'
import { ref } from 'vue'

interface UserInfo {
  userName?: string
  password?: string
}

export const useUserStore = defineStore('user', () => {
  // 1. 定义管理用户数据的state
  const userInfo = ref<UserInfo>({})
  const token = ref()

  // 2. 定义获取接口数据的action函数
  const getUserInfo = async ({ userName, password }: UserInfo) => {
    const res = await LoginApi.postLogin({ username: userName, password })
    // 存储 token 到浏览器缓存
    Session.set("token", res.data.access_token);
    // 存储用户信息到浏览器缓存
    const resU: any = await LoginApi.getUserInfo()
    userInfo.value = resU.user
    await Session.set("userInfo", resU.user);
    await Session.set("permissions", resU.permissions);
    await Session.set("roles", resU.roles);
    await setAddRoute()
    // 存储token到pinia
    token.value = res.data.access_token
  }
  // 退出时清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {}
    token.value = null
  }
  // 3. 以对象的格式把state和action return
  return {
    userInfo,
    token,
    getUserInfo,
    clearUserInfo
  }
}, {
  persist: true,
})